package com.mnxc.gxa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mnxc.gxa.dto.Result;
import com.mnxc.gxa.entity.Role;
import com.mnxc.gxa.entity.UserRole;
import com.mnxc.gxa.mapper.RoleMapper;
import com.mnxc.gxa.mapper.UserMapper;
import com.mnxc.gxa.mapper.UserRoleMapper;
import com.mnxc.gxa.service.IUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mnxc
 * @since 2023-06-29
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {
    @Resource
    UserMapper userMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    UserRoleMapper userRoleMapper;

    public UserRoleServiceImpl() {
    }

    public Result getRolesByUserId(Integer userId) {
        if (userId == null) {
            return Result.fail("参数错误");
        } else {
            LambdaQueryWrapper<UserRole> lqt = new LambdaQueryWrapper();
            lqt.eq(UserRole::getUserId, userId);
            List<UserRole> userRoles = this.userRoleMapper.selectList(lqt);
            return Result.ok(userRoles);
        }
    }

    public Result changeUserRoles(List<Long> roleIds, Long userId) {
        // 1.遍历角色id，判断角色信息是否存在
        for (Long roleId : roleIds) {
            // 1.1不存在，则报错
            Role role = roleMapper.selectById(roleId);
            if (role == null)  return Result.fail("角色信息不存在");
        }
        // 2.先删除旧的用户角色关系
        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId,userId);
        int deleteNum = userRoleMapper.delete(lqw);
        // 3.再添加新的用户角色关系
        roleIds.forEach(roleId->{
            userRoleMapper.insert(new UserRole(userId, roleId));
        });
        // 4.返回信息
        return Result.ok("配置角色信息成功！");

    }
}
